<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <input id="myFile" type="file" />
  <script>
    const $reader = (function (doc) {
      function Reader(id) {
        this.inputDom = doc.getElementById(id);
        this.files;
        this.type;
        this.myBlob = new Blob();
        this.myReader = new FileReader();
        this.init();
      }
      Reader.prototype.init = function () {
        this.myReader.onload = this.readerOnload.bind(this);
        this.myReader.onerror = this.readerOnerror.bind(this);
        this.myReader.onprogress = this.readerOnprogress.bind(this);
        this.bindEvent();
      }
      Reader.prototype.bindEvent = function () {
        this.inputDom.addEventListener("change", this.inputChange.bind(this), false);
      }
      Reader.prototype.readerOnload = function () {
        console.log('----------这是文件的内容------------');
        let html;
        if (this.type == 'image') {
          html = `<img src="${this.myReader.result}"/>`
        } else {
          html = `<span>${this.myReader.result}</span>`
        }
        document.body.innerHTML = html
      }
      Reader.prototype.readerOnerror = function () {
        new Error('读不到文件')
      }
      Reader.prototype.readerOnprogress = function (e) {
        console.log(e.loaded / e.total)
      }
      Reader.prototype.inputChange = function (event) {
        this.files = event.target.files;
        if (/image/.test(this.files[0].type)) {
          this.myReader.readAsDataURL(this.files[0])
          this.type = 'image'
        } else {
          const myBlob = this.files[0].slice(0, 5);
          this.myReader.readAsText(myBlob)
          this.type = 'text'
        }
      }
      return Reader;
    })(document);
    new $reader('myFile');
  </script>
</body>

</html>